package net.openl10n.packaging.document;

import net.openl10n.api.document.ContentTarget;
import net.openl10n.opc4j.PackagePart;
import net.openl10n.packaging.AbstractJaxbContentPart;
import net.openl10n.packaging.OpenLocPartContainer;
import net.openl10n.packaging.OpenLocPartFactory;
import net.openl10n.packaging.OpenLocPartFactoryManager;

public class ContentTargetPart extends AbstractJaxbContentPart{
	
	public static final String CONTENT_TYPE = "application/openl10n.document.target+xml";
	public static final String TARGET_NAME = "/target/#/content.xml";
	public static final String RELATIONSHIP_TYPE = "http://schemas.openl10n.net/document/target";
	
	private ContentTarget contentTarget;
	
	public static final OpenLocPartFactory<ContentTargetPart> FACTORY = 
		new OpenLocPartFactory<ContentTargetPart>() {
			@Override
			public ContentTargetPart create(OpenLocPartContainer container, PackagePart part, OpenLocPartFactoryManager partFactoryManager) {
				return new ContentTargetPart(container, part, partFactoryManager);
			}

			@Override
			public String getContentType() {
				return CONTENT_TYPE;
			}

			@Override
			public String getRelationshipType() {
				return RELATIONSHIP_TYPE;
			}

			@Override
			public Class<ContentTargetPart> getTargetClass(){
				return ContentTargetPart.class;
			}
			
			@Override
			protected String getPartNamePattern() {
				return TARGET_NAME;
			};
		};
	
	protected ContentTargetPart(OpenLocPartContainer container, PackagePart part, OpenLocPartFactoryManager partFactoryManager){
		super(container, part, partFactoryManager); 
	}

	public ContentTarget getContentTarget() {
		if(contentTarget == null)
			contentTarget = loadOrCreateJaxbObject(ContentTarget.class);
		return contentTarget;
	}
	
	public void setContentTarget(ContentTarget contentTarget) {
		this.contentTarget = contentTarget;
	}
	
	@Override
	protected void onClose() {
		if(contentTarget != null)
			saveJaxbObject(contentTarget);
		super.onClose();
	}
	
}
